import React, {Component} from 'react';
import {AsyncStorage, StyleSheet, TouchableOpacity, View, WebView} from 'react-native';
import FetchUtils from './../../utils/FetchUtils'
import utils from './../../utils/utils';

export default class IndexArticle extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: navigation.state.params ? navigation.state.params.title : null,
        headerTitleStyle: {
            alignSelf: 'center'
        },
        headerRight: <TouchableOpacity/>
    });

    constructor(prop) {
        super(prop);
        this.state = ({
            htmlView: null,
        })
    }

    componentDidMount() {

        let artId = this.props.navigation.state.params.articleId;
        let param = {
            id: artId
        };
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/index/article', xToken, param, (res) => {
                if (res.code == 200) {
                    console.log(res.apiData);
                    this.setState({
                        htmlView: res.apiData.artContent,
                    });

                    /*动态改变title*/
                    this.props.navigation.setParams({
                        title: res.apiData.title,
                    });
                }
            });
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <WebView
                    ref="webview"
                    automaticallyAdjustContentInsets={true}
                    bounces={false}
                    injectedJavaScript=
                        "
     var imgs = document.getElementsByTagName('img');
     for (var i = 0; i < imgs.length; ++i) {
        var img = imgs[i];
        img.style.maxWidth = '100%';
        img.style.height = 'auto';
     }
     "
                    javaScriptEnabled={true}
                    scalesPageToFit={true}
                    source={{html: this.state.htmlView}}
                    style={{width: '100%', height: '100%'}}>
                </WebView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },

});